#Alexander F. Gazmararian
#afg2@princeton.edu

#load packages
library(tidyverse)
library(scales)
library(modelsummary)
library(gridExtra)
library(grid)

#load custom functions
source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/coefnames4tables.r")
source("code/fun/fix_txt.r")

# Load and harmonize data
#load county fair data
fair <- readRDS("data/FairGazmararian_2022.rds")
fair$sample <- "County Fair"
fair <- fair %>%
  rename(
    Female = Gender,
    CollegeDegree = college
  )
fair <-
  fair %>%
  mutate(
    Black = ifelse(grepl("Black", Race), 1, 0),
    Hispanic = ifelse(grepl("Hispanic", Race), 1, 0),
    Minority_bin = case_when(grepl("^White$", Race) ~ 0, T ~ 1)
  )

#load winter 22 credibility
winter <- readRDS("data/NatQual_winter22.rds")

#load Caps-HarrisX wave 2
caps <- readRDS("data/NatCAPS_20220816.rds")
caps$weights <- caps$nweightNL33D_NEW2

#load youth national
youth <- readRDS("data/NatYouthQual.rds")
youth <- youth %>% rename(Ideo3 = Ideo_simple)
youth <- subset(youth, youth_block == "Youth")
youth$sample <- "Youth"
youth <- youth %>% mutate(Minority_bin = case_when(grepl("^White$", race) ~ 0, T ~ 1)) 
youth$weights <- 1

#civicpulse
cp <- readRDS("data/CivicPulse_Public.rds")
cp <- cp %>% rename(weights = Weight_1)
cp$sample <- ifelse(cp$Sample == "Standard", "Policymaker (National)", "Policymaker (Fossil Fuels)")
cp$Female <- ifelse(cp$Gender == "Woman", 1, 0)
cp <- cp %>%
  rename(
    age = Age,
    CollegeDegree = College
  )
cp$age <- NA
cp$age <- as.numeric(cp$age)
cp$Black <- NA
cp$Hispanic <- NA
cp <- cp %>% rename(Ideo3 = IdeoSimple)

#subset to relevant data
fair_sub <- subset(fair, select = c(weights, sample, Female, age, Black, Hispanic, Minority_bin, PartySummary, Ideo3, CollegeDegree, Investment, Investment_scale:Investment_uncertain, ff))
caps_sub <- subset(caps, select = c(weights, sample, Female, age, Black, Hispanic, Minority_bin, PartySummary, Ideo3, CollegeDegree, Investment, Investment_scale:Investment_uncertain))
youth_sub <- subset(youth, select = c(weights, sample, Female, age, Black, Hispanic, Minority_bin, PartySummary, Ideo3, CollegeDegree, Investment, Investment_scale:Investment_uncertain))
cp_sub <- subset(cp, select = c(weights, sample, Female, age, Black, Hispanic, Minority_bin, PartySummary, Ideo3, CollegeDegree, Investment, Investment_scale:Investment_uncertain))

#bind together
g <- bind_rows(fair_sub, caps_sub, youth_sub, cp_sub)

#recode covariates
g <- g %>%
  mutate(
    PartySummary = ifelse(PartySummary == "Not Say", "Neither", PartySummary),
    Ideo3 = ifelse(Ideo3 %in% c("Not Say", "Not sure", "Not Sure"), "Not Sure", Ideo3)
  )

# Create Figure 3.5 -----------------------------------------------------
lhs <-
  g %>%
  filter(sample == "CAPS") %>%
  mutate(Investment = ifelse(Investment_scale %in% c(1,2,3),
                             "Uncertain investment will continue or sure it will be reversed",
                             "Certain investment will continue")) %>%
  group_by(Investment) %>%
  summarise(n = sum(weights)) %>%
  mutate(pct = prop.table(n)) %>%
  ggplot(aes(x=Investment,y=pct,label=percent(pct, accuracy = 1))) +
  geom_col(position="dodge") +
  geom_text(position = position_dodge(.9), vjust = -.5, size = 3) +
  scale_x_discrete(labels = label_wrap(22)) +
  scale_y_continuous(labels = percent, expand = c(0,0), limits = c(0,.85)) +
  book_theme +
  scale_fill_grey() +
  labs(x = "", y = "", fill = "") +
  theme(legend.position = "bottom")
lhs
#from scale
rhs <-
  g %>%
  mutate(sample = ifelse(sample == "CAPS", "National", sample)) %>%
  mutate(sample = factor(sample, ordered = TRUE, levels = c("National", "Youth", "Policymaker (National)", "Policymaker (Fossil Fuels)", "County Fair"))
  ) %>%
  mutate(Investment_scale = (-1*Investment_scale+6)/5) %>%
  ggplot(aes(x=sample,y=Investment_scale,weight=weights)) +
  stat_summary(fun.data = "mean_cl_normal", geom="errorbar",width=0,position=position_dodge(.4)) +
  stat_summary(fun.data = mean_cl_normal, geom="errorbar",fun.args=list(conf.int=.9),width=0,size=1.75,position=position_dodge(.4)) +
  stat_summary(fun = mean, geom="point",size=4,position=position_dodge(.4)) +
  coord_flip(ylim=c(.5, .7)) +
  scale_y_continuous(labels = c("0.5\nLess Likely\nto Reverse", .55, .6, .65, ".7\nMore Likely\nto Reverse")) +
  scale_x_discrete(labels = label_wrap(15)) +
  book_theme +
  labs(y="", x="") +
  theme(plot.margin = margin(r=22))
rhs
gA <- ggplotGrob(rhs)
gB <- ggplotGrob(lhs)
maxWidth <- unit.pmax(gA$heights[2:5], gB$heights[2:5])
gA$heights[2:5] <- as.list(maxWidth)
gB$heights[2:5] <- as.list(maxWidth)
p.reduce <- grid.arrange(gB,gA,ncol=2)
savefig(p.reduce, "3.5_figure_govtcred", height = 1.9, filepath = "figures/")

# Estimate linear models for online appendix ----
invest.ols <- list()
##National
invest.ols[["National"]] <- lm(Investment_scale ~ age + Female + Hispanic + Black + CollegeDegree + PartySummary, caps, weight = weights)
##National youth
invest.ols[["Youth"]] <- lm(Investment_scale ~ age + Female + Hispanic + Black + PartySummary + CollegeDegree + CollegeIntend, youth)
##policymakers
invest.ols[["Policymaker"]] <- lm(Investment_scale ~ Age_cat + Woman + CollegeDegree + Minority_bin + PartySummary + Sample, cp, weight = weights)
##county fair
invest.ols[["County Fair"]] <- lm(Investment_scale ~ age + Female + Minority_bin + CollegeDegree + PartySummary + ff, fair)

##create table output
file <- "tables/ch3/ols_govcommit_investment.txt"
modelsummary(invest.ols,
             vcov = "HC2",
             gof_map = c("nobs", "adj.r.squared"),
             coef_map = coefnames,
             escape=FALSE,
             output = "latex",
             stars = c("*"=.1,"**"=.05,"***"=.01)
) %>%
  cat(., file = file)
fix_txt(file)
